#include "ds18b20.h"

static u8_t OneWire_Init()
{
	u8_t ret = 1;
	u8_t i = 0;
	
	DQ = 1;
	
	DQ = 0;
	
	i = 247;
	while (--i);
	
	DQ = 1;
	
	i = 32;
	while (--i);
	
	ret = DQ;
	
	i = 247;
	while (--i);
	
	return ret;
}


static void OneWire_Sendbit(u8_t Bit)
{
	u8_t i = 0;
	
	DQ = 0;
	
	i = 4;
	while (--i);
	
	DQ = Bit;
	
	i = 24;
	while (--i);
	
	DQ = 1;
}

static u8_t OneWire_Receivebit()
{
	u8_t ret = 1;
	u8_t i = 0;
	
	DQ = 0;
	
	i = 2;
	while (--i);
	
	DQ = 1;
	
	i = 2;
	while (--i);
	
	ret = DQ;
	
	i = 24;
	while (--i);
	
	return ret;
}


static void OneWire_Sendbyte(u8_t byte)
{
	u8_t i = 0;
	for(i = 0; i < 8; i++)
	{
		OneWire_Sendbit(byte&(0x01<<i));
	}
}

static u8_t OneWire_Receivebyte()
{
	u8_t ret = 0;
	u8_t i = 0;
	for(i = 0; i < 8; i++)
	{
		if(OneWire_Receivebit())
		{
			ret |= (0x01 << i);
		}
	}
	
	return ret;
}


void DS18B20_ConverT()
{
	OneWire_Init();
	OneWire_Sendbyte(0xCC);
	OneWire_Sendbyte(0x44);
}

float DS18B20_ReadT()
{
	int temp = 0;
	float T = 0.0;
	u8_t TLSB = 0;
	u8_t TMSB = 0;
	OneWire_Init();
	OneWire_Sendbyte(0xCC);
	OneWire_Sendbyte(0xBE);
	TLSB = OneWire_Receivebyte();
	TMSB = OneWire_Receivebyte();
	
	temp = (TMSB<<8) | TLSB;
	T = temp / 16.0;
	return T;
}

void Delay(unsigned int ms)
{
	unsigned char data i, j;

	while(ms--)
	{
		i = 2;
		j = 199;
		do
		{
			while (--j);
		} while (--i);
	}
}


void DS18B20_Init()
{
	DS18B20_ConverT();
	Delay(1000);
}

float get_temperature()
{
	float T = 0;
	DS18B20_ConverT();
	T = DS18B20_ReadT();
	return T;
}








